package com.dyz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dyz.domain.DTO.NoticeDTO;
import com.dyz.domain.Notice;

import com.dyz.mapper.NoticeMapper;
import com.dyz.mapper.SysUserMapper;
import com.dyz.model.Result;
import com.dyz.service.INoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统资讯公告信息 服务实现类
 * </p>
 *
 * @author dyz
 * @since 2025-04-19
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {
    @Resource
    private NoticeMapper noticeMapper;
    @Resource
    private SysUserMapper sysUserManager;

    @Override
    public Result<?> getNoticeList(Page<Notice> page, String title, String startTime, String endTime, Integer status) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<Notice> noticePage = noticeMapper.getNoticeList(page, title, startTime, endTime, status);
        return Result.success(noticePage);
    }

    @Override
    public Result<?> insertNotice(NoticeDTO noticeDTO) {
        Notice notice = new Notice();
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        String userName =sysUserManager.selectUserNameById(Long.valueOf(userId));
        noticeDTO.setAuthor(userName);
        BeanUtil.copyProperties(noticeDTO,notice);
        noticeMapper.insert(notice);
        return Result.success("新增成功");
    }

    @Override
    public Result<?> updateNotice(NoticeDTO noticeDTO) {
        Notice notice = new Notice();
        BeanUtil.copyProperties(noticeDTO,notice);
        int row = noticeMapper.updateById(notice);
        return row > 0 ? Result.success("修改成功") : Result.fail("修改失败");
    }

    @Override
    public Result<?> deleteNoticeByIds(String ids) {
        if(ids==null||ids.length()==0){
            return Result.fail("请选择要删除的数据");
        }
        String[] split = ids.split(",");
        List<Long> idList = Arrays.stream(split).map(Long::parseLong).collect(Collectors.toList());
        if(removeByIds(idList)){
            return Result.success("删除成功");
        }else{
            return Result.fail("删除失败");
        }
    }

    @Override
    public Result<?> updateStatusById(String id) {
        int row=noticeMapper.updateStatusById(id);
        return row>0?Result.success("修改成功"):Result.fail("修改失败");
    }

}
